package org.appFactory.carleton;

import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.appFactory.shared.CarletonOAuthService;
import org.appFactory.shared.Util;

@SuppressWarnings("serial")
public class CarletonOAuthHandler extends CarletonBaseListener implements ServletResponseAware {

	private HttpServletResponse response = null;

	public String state;
	public String code;
	public String access_token;
	public String redirectURL;
	public String serviceType;
	public String handlerName;
	
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	
	public String getCode() {
		return code;
	}
	
	public void setCode(String code) {
		this.code = code;
	}
	
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public HttpServletResponse getServletResponse() {
		return this.response;
	}

	public String getRedirectURL() {
		return redirectURL;
	}
	
	public void setRedirectURL(String redirectURL) {
		this.redirectURL = redirectURL;
	}

	public String getAccess_token() {
		return access_token;
	}
	
	public void setAccess_token(String access_token) {
		this.access_token = access_token;
	}
	
	public String getServiceType() {
		return serviceType;
	}
	
	public void setServiceType(String service) {
		this.serviceType = service;
	}
	
	
	public String getHandlerName() {
		return handlerName;
	}
	
	public void setHandlerName(String handlerName) {
		this.handlerName = handlerName;
	}
	
	public String execute() {
		
		if (code != null && !code.isEmpty() && serviceType !=null )  {
			String accessToken = null;
			CarletonOAuthService service = null;
			
			if (serviceType.equals("facebook"))
				service = (CarletonOAuthService) getFacebookService();
						
			//Now Exchange the Code
			if(service != null)
				accessToken = service.exchangeCodeForToken(code, getBaseURL() + handlerName);
			
			//Check if access Token is null
			if (accessToken == null)
				return ERROR; 
			
			System.out.println(service + " Access Token :" + accessToken);
			Util.putSessionObj(accessToken, service.getAccessTokenKey());
			return SUCCESS;
		}


		
		return ERROR;
	}
}
